import COS from 'cos-js-sdk-v5'
import { v4 as uuidv4 } from 'uuid'
import { cosApi } from '@/api'

let cosInstance = null
let cosConfig = null

const initCOS = async () => {
  try {
    const credentials = await cosApi.getTempSecret({})

    cosConfig = {
      bucket: credentials.bucket,
      region: credentials.region
    }

    cosInstance = new COS({
      getAuthorization: function (options, callback) {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          SecurityToken: credentials.sessionToken,
          StartTime: credentials.startTime,
          ExpiredTime: credentials.expiredTime
        })
      }
    })

    return { cos: cosInstance, config: cosConfig }
  } catch (error) {
    console.error('初始化COS失败:', error)
    throw error
  }
}

export const uploadByType = async (file, type = 'photo') => {
  try {
    const { cos, config } = await initCOS()

    const fileExtension = file.name.split('.').pop()
    const fileName = `${type}/${uuidv4()}.${fileExtension}`

    return new Promise((resolve, reject) => {
      cos.putObject({
        Bucket: config.bucket,
        Region: config.region,
        Key: fileName,
        Body: file,
        onProgress: function(progressData) {
          console.log('上传进度:', progressData.percent)
        }
      }, function(err, data) {
        if (err) {
          console.error('上传失败:', err)
          reject(err)
        } else {
          const url = `https://${data.Location}`
          console.log('上传成功:', url)
          resolve(url)
        }
      })
    })
  } catch (error) {
    console.error('上传文件失败:', error)
    throw error
  }
}